package com.dja.nzw.mq.kafka.simple;

import kafka.consumer.ConsumerConfig;
import kafka.consumer.ConsumerIterator;
import kafka.consumer.KafkaStream;
import kafka.javaapi.consumer.ConsumerConnector;
import kafka.serializer.StringDecoder;
import kafka.utils.VerifiableProperties;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

/**
 * Created by shuyun on 2017/7/12.
 */
public class SimpleConsumer {

    public static void main(String[] args) throws Exception {
        String TOPIC = "dja-topic";
        ConsumerConnector consumer = null;

        try {
            Properties prop = new Properties();
            // zookeeper 配置
            prop.put("zookeeper.connect", "172.18.2.177:2181,172.18.2.178:2181,172.18.2.179:2181");
            // group 代表一个消费组
            prop.put("group.id", "jd-group");
            // zk连接超时
            prop.put("zookeeper.session.timeout.ms", "4000");
            prop.put("zookeeper.sync.time.ms", "200");
            prop.put("auto.commit.interval.ms", "1000");
            prop.put("auto.offset.reset", "smallest");
            // 序列化类
            prop.put("serializer.class", "kafka.serializer.StringEncoder");

            ConsumerConfig config = new ConsumerConfig(prop);
            consumer = kafka.consumer.Consumer.createJavaConsumerConnector(config);
            Map<String, Integer> topicCountMap = new HashMap();
            topicCountMap.put(TOPIC, new Integer(1));

            Map<String, List<KafkaStream<String, String>>> consumerMap = consumer.createMessageStreams(topicCountMap,
                    new StringDecoder(new VerifiableProperties()),
                    new StringDecoder(new VerifiableProperties()));

            List<KafkaStream<String, String>> streams = consumerMap.get(TOPIC);

            streams.stream().forEach(stream -> {
                ConsumerIterator<String, String> it = stream.iterator();
                while (it.hasNext()) {
                    System.out.println(new String(it.next().message()));
                }
            });
        } catch (Exception ex) {
            ex.printStackTrace();
            System.exit(-1);
        } finally {
            if(null != consumer)
                consumer.shutdown();
        }
    }
}
